package com.hnust.wswx.moblieStuBack.controller;

import com.hnust.wswx.moblieStuBack.util.R;
import lombok.extern.slf4j.Slf4j;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;

@RestController
@RequestMapping("/test")
@Slf4j
public class uploadController {

    @Value("${pic.url}")
    private String path;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @CrossOrigin(origins="*",maxAge=3600)
    @PostMapping("/upload")
    public R<String> upload(
            @RequestParam("userId")String userId,
             @RequestParam("questionId")String questionId,
             @RequestParam("file") MultipartFile file){
        // 拼接服务区的文件路径
        log.info("用户ID:{},题目ID:{}",userId,questionId);
        StringBuilder sbPath = new StringBuilder();
        sbPath.append("http://").append(path).append("/");
        String ext_Name = Objects.requireNonNull(file.getOriginalFilename()).split("\\.")[1]; //png
        String file_Name = file.getOriginalFilename().split("\\.")[0];//机器人
        log.info("文件名:{}.{}",file_Name,ext_Name);
        String fileId=redisTemplate.opsForValue().get(userId+"+"+questionId);
        byte[] bytes = null;
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(fileId!=null){
            fileId = uploadFile(bytes, ext_Name, file_Name,
                    userId+"+"+questionId,true,fileId);
        }else{
            fileId = uploadFile(bytes, ext_Name, file_Name,
                    userId+"+"+questionId,false,null);
        }
        sbPath.append(fileId);
        return R.success(sbPath.toString());
    }
    private String uploadFile(byte[] byteFile, String ext_file,
                              String file_Name, String originFileName,
                             boolean isDelete, String deleteFileId) {
        try {
            //加载fastDFS客户端的配置文件
            ClientGlobal.initByProperties("config/fastdfs-client.properties");
            //创建tracker的客户端
            TrackerClient tracker = new TrackerClient();
            TrackerServer trackerServer = tracker.getConnection();
            StorageServer storageServer = null;
            //定义storage的客户端
            StorageClient1 client = new StorageClient1(trackerServer, storageServer);
            //文件元信息
            NameValuePair[] metaList = new NameValuePair[1];
            metaList[0] = new NameValuePair("fileName", file_Name+"."+ext_file);
            //通过文件字节流执行上传
            if(isDelete){
                client.delete_file1(deleteFileId);
            }
            String fileId=client.upload_file1(byteFile, ext_file, metaList);
            System.out.println("upload success. file id is: " + fileId);
            //关闭trackerServer的连接
            trackerServer.close();
//            log.debug("上传路径=" + sbPath.toString());
            redisTemplate.opsForValue().set(originFileName,fileId);
            return fileId;
        } catch (IOException | MyException e) {
            e.printStackTrace();
            return null;
        }
    }
}
